package com.xuan_poi.easy;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * @author renzhengxuan
 * @date 2021/4/12
 */
@Slf4j
public class EasyWriteTest {
    //假设这是数据库查询出的集合
    public List<DemoData> data() {
        List<DemoData> list = new ArrayList<DemoData>();
//        for (int i = 0; i < 10; i++) {
        DemoData data = new DemoData();
        data.setString(null);
        data.setDate(new Date());
        data.setDoubleData(0.56);
        list.add(data);
        DemoData data1 = new DemoData();
        data1.setString("花花");
        data1.setDate(new Date());
        data1.setDoubleData(0.56);
        list.add(data1);
//        }
        return list;
    }
    public List<Student> studentList(){
        List<Student> list=new ArrayList<>();
        list.add(new Student("1","张三","男",22,null));
        list.add(new Student("2","李四",null,11,null));
        list.add(new Student("3","小猫","女",15,null));
        return list;
    }

    /**
     * 最简单的写
     * <p>1. 创建excel对应的实体对象 参照{@link DemoData}
     * <p>2. 直接写即可
     * 导入一个sheet
     */
    @Test
    public void simpleWrite() {
        // 写法1
        String fileName = "D:\\excel\\easy.xlsx";
        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(fileName, DemoData.class).sheet().doWrite(data());
    }

    /**
     * 导出多个sheet
     *
     * @throws Exception
     */
    @Test
    public void exportSheets() throws Exception {
        String fileName = "D:\\excel\\exportSheets.xlsx";
        OutputStream os = new FileOutputStream(fileName);
        //写入一个工作簿
        ExcelWriter excelWriter = EasyExcel.write(os).build();
        excelWriter.write(data(), EasyExcel.writerSheet("学生表1").head(DemoData.class).build());
        excelWriter.write(data(), EasyExcel.writerSheet("学生表").head(DemoData.class).build());
        //千万别忘记关闭，finish也会顺便关闭流
        excelWriter.finish();
    }

    public <T> void exportExcel(String path,Class<T> entity,List<T> list){
        //定义导出的路径
//        String PATH="D:\\excel\\aa.xls";
        //导出
        EasyExcel.write(path,entity).useDefaultStyle(true).sheet().doWrite(list);
    }
    @Test
    public void export(){
        String PATH="D:\\excel\\bb.xls";
        new EasyWriteTest().exportExcel(PATH,Student.class,studentList());
    }
    @Test
    public void export_Sheets(){
        String PATH="D:\\excel\\aa.xlsx";
        ExcelWriter excelWriter = EasyExcel.write(PATH).build();
        excelWriter.write(null,EasyExcel.writerSheet(1,"数据表").head(DemoData.class).build());
        excelWriter.write(null,EasyExcel.writerSheet(0,"学生表").head(Student.class).build());
        excelWriter.finish();
    }
}
